﻿using System.Web;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Shinkansen.Runtime
{
    public class QueryString : Dictionary<string, string>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="QueryString"/> class.
        /// </summary>
        public QueryString () { }

        /// <summary>
        /// Initializes a new instance of the <see cref="QueryString"/> class.
        /// </summary>
        /// <param name="queryString">The query string.</param>
        public QueryString (string queryString)
        {
            if (string.IsNullOrEmpty (queryString))
                return;

            MatchCollection matches = Regex.Matches (queryString, @"(\w*)\=([^&]*)");
            foreach (Match match in matches)
            {
                string key = match.Groups[1].Value,
                       value = match.Groups[2].Value;

                this.Add (key, HttpUtility.UrlDecode (value, Encoding.UTF8));
            }
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString ()
        {
            string[] tokens = this
                .Select (pair => pair.Key + "=" + HttpUtility.UrlEncode (pair.Value, Encoding.UTF8))
                .ToArray ();

            return string.Join ("&", tokens);
        }
    }
}